package top.andnux.weather.fragment;

import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.PickVisualMediaRequest;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;

import com.blankj.utilcode.util.UriUtils;

import java.io.File;
import java.io.IOException;
import java.util.List;

import cn.piesat.bottomdialog.ActionSheetDialog;
import top.andnux.weather.adapter.PhotoAdapter;
import top.andnux.weather.controller.PhotoController;
import top.andnux.weather.databinding.FragmentPhotoBinding;
import top.andnux.weather.view.PhotoView;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class PhotoFragment extends BaseFragment<FragmentPhotoBinding> implements PhotoView {

    private static final String TAG = "PhotoFragment";
    private PhotoController controller;
    private PhotoAdapter adapter;
    private ActivityResultLauncher<PickVisualMediaRequest> pickMedia;
    private ActivityResultLauncher<Uri> takePicture;
    private File file;

    @Override
    protected FragmentPhotoBinding createViewBinding(LayoutInflater inflater) {
        return FragmentPhotoBinding.inflate(inflater);
    }


    private final OnCompressListener compressListener = new OnCompressListener() {
        @Override
        public void onStart() {
            Log.d(TAG, "onStart() called");
        }

        @Override
        public void onSuccess(File file) {
            Log.d(TAG, "onSuccess() called with: file = [" + file + "]");
            controller.addImage(file);
        }

        @Override
        public void onError(Throwable e) {
            Log.d(TAG, "onError() called with: e = [" + e + "]");
        }
    };

    @Override
    protected void onCreated(@Nullable Bundle savedInstanceState) {
        controller = new PhotoController(requireContext());
        controller.attachView(this);
        adapter = new PhotoAdapter();
        binding.content.setAdapter(adapter);

        binding.add.setOnClickListener(v -> {
            ActionSheetDialog dialog = new ActionSheetDialog(requireContext()).builder();
            dialog.setCancelable(true).setCanceledOnTouchOutside(true).addSheetItem("拍照",
                    ActionSheetDialog.SheetItemColor.Normal,
                    which -> takePhoto()).addSheetItem("相册", ActionSheetDialog.SheetItemColor.Normal,
                    which -> selectPhoto()).show();
        });

        pickMedia = registerForActivityResult(new ActivityResultContracts.PickVisualMedia(), uri -> {
            if (uri != null) {
                File file = UriUtils.uri2File(uri);
                Log.d("PhotoPicker", "Selected file: " + file.getAbsolutePath());
                Luban.with(requireContext())
                        .load(file)
                        .ignoreBy(100)
                        .setTargetDir(context.getFilesDir().getAbsolutePath())
                        .filter(path -> !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif")))
                        .setCompressListener(compressListener).launch();
            } else {
                Log.d("PhotoPicker", "No media selected");
            }
        });

        takePicture = registerForActivityResult(new ActivityResultContracts.TakePicture(), success -> {
            Log.d("TakePicture", "TakePicture status: " + success);
            if (success) {
                Luban.with(context)
                        .load(file)
                        .ignoreBy(100)
                        .setTargetDir(context.getFilesDir().getAbsolutePath())
                        .filter(path -> !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif")))
                        .setCompressListener(compressListener).launch();
            }
        });
        controller.loadImages();
    }

    private void selectPhoto() {
        pickMedia.launch(new PickVisualMediaRequest.Builder()
                .setMediaType(ActivityResultContracts.PickVisualMedia.ImageOnly.INSTANCE)
                .build());
    }

    private void takePhoto() {
        File dir = context.getExternalCacheDir();
        if (!dir.exists()) {
            dir.mkdirs();
        }
        file = new File(dir, System.currentTimeMillis() + ".jpg");
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Uri tmp = UriUtils.file2Uri(file);
        takePicture.launch(tmp);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (controller != null) {
            controller.detachView();
            controller = null;
        }
    }

    @Override
    public void showPhoto(List<String> list) {
        adapter.submitList(list);
    }
}